package com.jediflasher.game_server.services

import java.io.DataOutputStream
import com.jediflasher.game_server.messages.MessageWrapper
import java.lang.Boolean
import com.jediflasher.game_server.messages.RequestMessageLogin.LoginResponse.{Builder, LoginResponseStatus}
import com.jediflasher.game_server.util.log.Logger
import java.sql.ResultSet
import com.jediflasher.game_server.database.DataBaseManager
import com.jediflasher.game_server.messages.RequestMessageLogin.{LoginResponse, LoginRequest}
import com.jediflasher.game_server.messages.HeaderMessage.{MessageType, ServiceType}
import com.jediflasher.game_server.messages.ServiceMethodLogin.MethodLogin
import com.jediflasher.game_server.data.{SuperUserData, WorldData}

/**
 * User: Obi
 * Date: 14.07.11
 * Time: 21:16
 */

class ServiceLogin(out: DataOutputStream, worldData: WorldData, superUser: SuperUserData) extends AbstractService(out, worldData, superUser) {

	def process(messageWrapper: MessageWrapper) {
		messageWrapper.message match {
			case m: LoginRequest => processLogin(messageWrapper);
		}
	}

	def processLogin(messageWrapper: MessageWrapper) {
		val message: LoginRequest = messageWrapper.message.asInstanceOf[LoginRequest];
		Logger.log("login message received. login:" + message.getLogin + " password:" + message.getPassword);

		val query = "SELECT * FROM users WHERE name='" + message.getLogin + "' AND password='" + message.getPassword + "'";
		val result: ResultSet = DataBaseManager.executeQuery(query);

		val ok: Boolean = result.next();
		val builder: Builder = LoginResponse.newBuilder();

		if (ok) {
			val userId: Int = result.getInt("id");
			superUser.id = userId;

			builder.setStatus(LoginResponseStatus.OK).setUserId(userId);
		}
		else {
			builder.setStatus(LoginResponseStatus.ERROR);
		}

		super.send(builder.build(), MessageType.RESPONSE, MethodLogin.LOGIN_VALUE, messageWrapper.requestId);

		if (ok) worldData.addUser(superUserId, result);
	}

	override def getServiceType = ServiceType.LOGIN;

}
